package com.qf.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsStorageMapper;
import com.qf.pojo.DtsStorage;
import com.qf.util.AliyunOSSUtil;
import com.qf.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class StorageServiceImpl implements StorageService {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Autowired
    private DtsStorageMapper storageMapper;

    @Override
    public DtsStorage add(String fileName, String ext, long size, byte[] context) throws Exception {
        //1、生产一个随机字符串作为文件名
        String key = UUID.randomUUID().toString();
        //2、随机的字符串+ 文件扩展名组成文件名称
        String newfileName = key + ext;
        //3、文件上传到阿里云
        String url = AliyunOSSUtil.uploadImage(endpoint, accessKeyId, accessKeySecret, bucketName, newfileName, context);

        DtsStorage storage = new DtsStorage();
        storage.setKey(key);
        storage.setAddTime(new Date());
        storage.setName(newfileName);
        storage.setDeleted(false);
        storage.setSize((int) size);
        storage.setUpdateTime(new Date());
        storage.setUrl(url);
        storage.setType(ext);

        int count = storageMapper.insert(storage);

        return storage;
    }

    @Override
    public IPage<DtsStorage> queryByPage(Integer page, Integer limit,
                                         String sort, String order,
                                         String key, String name) {

        //分页对象, 第一参数: 当前页, 第二参数: 每页显示条数
        IPage<DtsStorage> iPage = new Page<>(page, limit);
        //条件对象
        QueryWrapper<DtsStorage> queryWrapper = new QueryWrapper<>();

       if (!StringUtils.isEmpty(key)){
           queryWrapper.eq("key",key);
       }
       if (!StringUtils.isEmpty(name)){
           queryWrapper.like("name",name);
       }
        //排序
       if ("asc".equalsIgnoreCase(order)){
           queryWrapper.orderByAsc(sort);
       }else {
           queryWrapper.orderByDesc(sort);
       }

        IPage<DtsStorage> storageIPage = storageMapper.selectPage(iPage, queryWrapper);
        return storageIPage;
    }
}
